package com.irdstudio.efp.esb.api.rest.sx;


import java.util.Date;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.efp.esb.api.bean.sx.ReqQueryBean;
import com.irdstudio.efp.esb.api.bean.sx.RespQueryBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.common.constant.PrdInfoEnum;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.irdstudio.efp.esb.api.common.TransactionTypeEnum;

/**
 * 网贷授信查询接口
  * @author heyingfeng
  * @since 2019年3月4日 下午2:52:38
  * @version 1.0
 */
@RestController
@RequestMapping("/esb")
public class NlsQueryBDController {
	private static Logger logger = LoggerFactory.getLogger(NlsQueryBDController.class);

	/**
	 * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:28:08
	 * @version 1.0
	 */
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("校验 ESB请求系统头和请求应用头对象!");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	/**
	 * 获取ESB请求对象，校验 ESB请求体对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:31:14
	 * @version 1.0
	 */
	@ModelAttribute("reqQueryBean")
	public ReqQueryBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("校验 ESB请求体对象！");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqQueryBean.class);
	}

	/**
	 * 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息<br>
	 * 2.调用对应的中台服务<br>
	 * 3.增加调用队列任务表信息<br>
	 * TODO:此处为统一的进件交易，先暂时不按照产品代码进行划分，后续根据差异化需求决定是否拆分；
	 * 
	 * @param esbReqServiceBean
	 *            ESB请求对象
	 * @param br1
	 * @param reqCreditBean
	 *            ESB请求体的对象
	 * @param br2
	 * @param exception
	 *            切面的异常信息
	 * @return
	 * @throws Exception
	 * @author huangwb
	 * @since 2019年1月20日 下午2:20:51
	 * @version 1.0
	 */
	@PostMapping("/SERVICE_30230005_01")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
			@Validated @ModelAttribute("reqQueryBean") ReqQueryBean reqQueryBean, BindingResult br2, Exception exception) throws Exception {
		String applSeq = reqQueryBean.getAppFlowNo();//流水号--reqSn
		String channelNo = reqQueryBean.getChanFlg();//渠道
		String baiduSnId = reqQueryBean.getBaiduSnId(); //会话ID
		String evID = reqQueryBean.getEvID(); //事务ID
		NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
		try {
			// 通过切面校验进件申请参数是否正确，如不正确则返回错误信息
			if (Objects.nonNull(exception)) {
				throw exception;
			}
			if("05".equals(channelNo)) {//度小满
					nlsCreditInfoVO.setBdReqSn(applSeq);
					nlsCreditInfoVO = nlsCreditInfoService.queryByPk(nlsCreditInfoVO);
					if (nlsCreditInfoVO == null) {
						throw new BizException("无授信数据");
					}
					return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
							JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "查询成功", nlsCreditInfoVO)), //
							EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
							EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), //
							"查询成功");
			}
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), "非百度渠道", nlsCreditInfoVO)), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
					"非百度渠道");
		} catch (BizException e) {
			logger.error("授信查询服务接口处理成功!" + e.getMessage());
			e.printStackTrace();
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage(), nlsCreditInfoVO)), //
					EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
					EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
					e.getMessage());
		} catch (Exception e) {
			logger.error("授信查询服务接口处理失败!" + e.getMessage());
			e.printStackTrace();
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage(), nlsCreditInfoVO)), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
					e.getMessage());
		}
	}

	/**
	 * 组织用户借款请求接口的返回对象
	 * 
	 * @param retStCd
	 *            返回状态码
	 * @param retMsg
	 *            返回信息
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:59:46
	 * @version 1.0
	 */
	private RespQueryBean buildRespCreditBean(String baiduSnId,String evID,String retCd, String retMsg, NlsCreditInfoVO nlsCreditInfoVO) {
		RespQueryBean respQueryBean = new RespQueryBean();
		respQueryBean.setRetCd(retCd);
		respQueryBean.setRetMsg(retMsg);
		if(EsbBizEnums.RetCodeEnum.SUCCESS.VALUE.equals(retCd)) {
			respQueryBean.setRetStCd(nlsCreditInfoVO.getApprvSts());//01：处理中 02：通过 03：拒绝 04：取消 05：挂起 06：审批作废
			if(!BaseConstant.NLS_APPLY_STATE_02.equals(nlsCreditInfoVO.getApprvSts()) &&
					!BaseConstant.NLS_APPLY_STATE_01.equals(nlsCreditInfoVO.getApprvSts())) {//不通过
				respQueryBean.setbDRsnCd(nlsCreditInfoVO.getBdReasonCode());//百度原因码
				respQueryBean.setbDRsnCdDsc(nlsCreditInfoVO.getBdReasonMsg());//原因码描述
			}
			respQueryBean.setEvTp(TransactionTypeEnum.APPLY.getValue());//事务类型
			respQueryBean.setEvID(evID);//事务ID
			respQueryBean.setBaiduSnId(baiduSnId);//会话ID
			String timeStamp = TimeUtil.getTimeStampByPattern("yyyyMMddHHmmssSSS"); //时间戳
			respQueryBean.setTxnTmstmp(timeStamp);//时间戳
			respQueryBean.setCertNo(nlsCreditInfoVO.getCertCode());//证件码
			respQueryBean.setBankCardNo(nlsCreditInfoVO.getRecvAccount());//银行卡
			respQueryBean.setCustNm(nlsCreditInfoVO.getCusName());//客户姓名
			respQueryBean.setMblNo(nlsCreditInfoVO.getIndivMobile());//手机号
			if(BaseConstant.NLS_APPLY_STATE_02.equals(nlsCreditInfoVO.getApprvSts())) {//通过
				respQueryBean.setCrdtLmt(nlsCreditInfoVO.getApplyAmt()+"");//授信额度
				if(PrdInfoEnum.MYD.getPrdId().equals(nlsCreditInfoVO.getPrdCode()) ) {
					respQueryBean.setLmtTrm("30");//满易贷30天
				}else {
					respQueryBean.setLmtTrm("7");//尊享贷7天
				}
				respQueryBean.setLmtTrmUnt(MsLoanConstant.TermTypeMap.get(nlsCreditInfoVO.getTermType()));//额度期限单位
			}
		}
		return respQueryBean;
	}
	
	@Autowired
	@Qualifier("nlsCreditInfoService")
	private NlsCreditInfoService nlsCreditInfoService;
}
